<template>
  <div class="home">
    <div class="header">
      <div class="container">
        <div v-if="username != null">
          <a class="loginout" @click="doLoginout">登出</a>
          <a class="manage" v-if="roleType === 0" @click="goToBackend"
            >后台管理</a
          >
          <div class="username">{{ username }}</div>
        </div>
        <div v-else>
          <a class="login" @click="goToLogin">登录</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { checkLogin, logout } from "@/api/user.js";
export default {
  name: "top",
  data() {
    return {
      username: null,
      roleType: null,
      roleName: null,
    };
  },
  methods: {
    goToLogin() {
      this.$router.push({ path: "/login" });
    },
    goToBackend() {
      this.$router.push({ path: "/backend" });
    },
    check() {
      checkLogin()
        .then((res) => {
          if (res == null) {
            this.username = null;
            this.roleType = null;
            this.roleName = null;
            return;
          }
          this.username = res.name;
          this.roleType = res.roleType;
          this.roleName = res.roleName;
        })
        .catch((errMsg) => this.$alert(errMsg.msg));
    },
    doLoginout() {
      logout()
        .then((res) => {
          this.username = null;
          this.roleType = null;
          this.roleName = null;
          if (this.$route.path.includes("backend")) {
            this.$router.push({ path: "/" });
          }
        })
        .catch((errMsg) => this.$alert(errMsg.msg));
    },
  },
  mounted() {
    this.check();
  },
};
</script>
<style lang="stylus" scoped>
.home {
  .header {
    height: 40px;
    min-width: 1024px;
    background-color: #ccc;

    .container {
      width: 1024px;
      margin: 0 auto;
      line-height: 40px;
      user-select: none;

      .username {
        float: right;
        margin-right: 20px;
        font-size: 14px;
        cursor: default;
      }

      .manage {
        float: right;
        cursor: pointer;
        padding: 0 5px;
        color: #E6A23C;

        &:hover {
          background-color: #333;
          color: #fff;
        }
      }

      .login {
        float: right;
        margin-right: 20px;
        cursor: pointer;
        padding: 0 10px;

        &:hover {
          background-color: #67C23A;
          color: #fff;
        }
      }

      .loginout {
        margin-left: 15px;
        float: right;
        color: #F56C6C;

        &:hover {
          background-color: #333;
          color: #fff;
        }
      }
    }
  }
}
</style>
